 $(function(){
      $("#header").load("header.html");
      laydate.render({
         elem:'#tar_begin',
         max:0,
         done:function(value,date){
             console.log(value);
         }
      });
      laydate.render({
         elem:'#tar_end',
         max:1,
         done:function(value,date){
             console.log(value);
         }
      });
      $(document.body).css({
        "overflow-x":"hidden"
        });
     var domain='lv';
     //获取cookie中的domain用于多站点
//      var domain=$.cookie('domain');
//      console.log(domain);
      listDomArr = [],
      currIndex = 3, 
      currTimes="0",
      miniRefreshArr = [];
      var windowWidth=$(document.body).width();
      var bindEvent=Tool.bindEvent;
      var addToken=Tool.addTokenToParams;
      var chartview0 = echarts.init(document.getElementById('chart0'));
      var chartview1 = echarts.init(document.getElementById('chart1'));
      var chartview2 = echarts.init(document.getElementById('chart2'));
      var chartview3 = echarts.init(document.getElementById('chart3'));
      var dz_obj={今天:'0',昨天:'-1',最近7天:'-7',最近30天:'-30'};
      //时间选择器
      $("#pt_select").val('今天');
      $("#pt_select").bind("change",function(){
          currTimes=dz_obj[$(this).val()];
          var type='1',times=currTimes,index=currIndex;
          if(index==1)
             type='2';
          else if(index==2)
             type='4';
          else if(index==3)
              type='5';
          listDomArr[index] = '#chart' + index;
          var jparms={type:type,times:times,chart:listDomArr[index],index:index};
          requestform(jparms);
           
      });
      //时间筛选
      $("#timesend").click(function(){
         var beginDate=$("#tar_begin").val();
         var endDate=$("#tar_end").val();
         if(beginDate==null||beginDate.trim().length==0){
             alert("筛选开始时间不能为空");
             return;
         }
         if(endDate==null||endDate.trim().length==0){
             alert("筛选结束时间不能为空");
             return;
         }
        var timeRange=beginDate+"/"+endDate;
        var type='1',times=timeRange,index=currIndex;
        if(index==1)
            type='2';
        else if(index==2)
            type='4';
        else if(index==3)
            type='5';  
        listDomArr[index] = '#chart' + index;
        var jparms={type:type,times:times,chart:listDomArr[index],index:index};
        requestform(jparms);
       
      });
      var requestform =function(rs_data){
          if(typeof(domain)!='undefined'){
              rs_data.domain=domain; //添加当前的网站域名 用以读取不同站点的数据
          }
          var chartIndex=rs_data.type;
          var chartTitle='流量统计',chartPlot='line',chartId=rs_data.chart;
          if(chartIndex=='2'){
              chartTitle='流量来源';
              chartPlot='bar';
          }   
          else if(chartIndex=='4'){
               chartTitle='流量分布';
                chartPlot='line';
          }else if(chartIndex=='5'){
              chartTitle='销售统计';
              chartPlot='line';
          }  
          var jobj={cahrtId:chartId,chartTitle:chartTitle,chartPlot:chartPlot,index:rs_data.index};
          $.ajax({
                url:doGetNewChartData,
                type:"POST",
                data:JSON.stringify(addToken(rs_data)),
                contentType:"application/json;charset=UTF-8",
    		    xhrFields: {
    		    withCredentials: true
    		          },
    		    crossDomain: true,
                beforeSend:function(xhr){
                    showLoading();
                    //发送请求前运行的函数
                },
                success:function(result){
                    hideLoading();
                    var seriesData=result.data.series;
                    var xdata=seriesData.xdata;
                    var ydata=seriesData.ydata;
                    drawCharts(xdata,ydata,jobj);
                    fillContents(result.data,rs_data.index,null);   
        
                },
                error:function(xhr,status,error){
                    hideLoading();
                    alert(status.toString()+'链接错误或超时!')
                }
            });
      };
      function fillContents(data,index,detail){
          if(index==0){
              $("#pv_val").text(data.pv);
              $("#pp_val").text(data.average_pv);
              $("#ip_val").text(data.ip);
              $("#uv_val").text(data.uv);
              $("#scan_tb").children().each(function(){
                       $(this).remove(); 
                    });
              
              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value.title+'</td>' +
                    '<td>'+value.pv+'</td>' +
                    '<td>'+value.average_pv+'</td>' +
                    '<td>'+value.ip+'</td>' +
                    '<td>'+value.uv+'</td>' +
                    '</tr>';
                });
              $("#scan_tb").append(html);   
              
          }else if(index==1){
              $("#plat_tb").children().each(function(){
                       $(this).remove(); 
                    });
              
              var html = '';
              $.each(data, function (key, value) {
                    html += '<tr>'+
                    '<td><span class="plat_det">'+value.title+'</span></td>' +
                    '<td>'+value.pv+'</td>' +
                    '<td>'+value.average_pv+'</td>' +
                    '<td>'+value.ip+'</td>' +
                    '<td>'+value.uv+'</td>' +
                    '</tr>';
                });
              $("#plat_tb").append(html);
              $(".plat_det").click(function(){
                 var spantxt=$(this).text();
                 var keyword=keywordByTxt(spantxt);
                 var detailData=detail[keyword];
                 var keydata=JSON.stringify(detailData);
                 localStorage.keydata=keydata;
                 $.cookie('keyname', spantxt);
                 window.location='detailLink.html';
                
              });
              function keywordByTxt(name){
                    var key='other';
                    if(name=='直接输入'){
                        key='enter_directly'
                    }else if(name=='社交平台'){
                        key='share_platform';
                    }else if(name=='搜索引擎'){
                        key='search_engine';
                    }
                  return key;
              }
          }else if(index==2){
              $("#country_tb").children().each(function(){
                       $(this).remove(); 
                    });
              
              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value.title+'</td>' +
                    '<td>'+value.pv+'</td>' +
                    '<td>'+value.average_pv+'</td>' +
                    '<td>'+value.ip+'</td>' +
                    '<td>'+value.uv+'</td>' +
                    '</tr>';
                });
              $("#country_tb").append(html);     
          }
          else{
              $("#total_rev").text("平台总销售额:"+data.totalRev+"美元");
              $("#total_ord").text("平台总订单量:"+data.totalOrd+"单");
              var seriesData=data.series;
              var revenue=seriesData.rangeRevenue;
              var order=seriesData.rangeOrder;
              $("#ddje").text(revenue);
              $("#dddj").text('订单单价:'+(parseFloat(revenue)/parseInt(order)).toFixed(2));
              $("#ddsl").text('订单数量:'+order);
              $("#kdj").text(seriesData.rangeUser);
              //$("#xdrs").text('下单人数:'+data.order_customer_count);
              //$("#zhl").text(data.ratio);
              //$("#fkrs").text('访客人数:'+data.visit_customer);
              //$("#yhje").text(data.discount_price);
              //$("#sycs").text('使用次数:'+data.coupon_count);
             
              
          }
      }

      var initMiniRefreshs = function(index) {
            //listDomArr[index] = document.querySelector('#listdata' + index);
            listDomArr[index] = '#chart' + index;
            var type='1',times=currTimes;
            if(index==1)
                type='2';
            else if(index==2)
                type='4';
            else if(index==3){
                type='5';
            }
            var jparms={type:type,times:times,chart:listDomArr[index],index:index};
            requestform(jparms);
            
          
    };   
     var navControl = document.querySelector('.nav-control'),CLASS_HIDDEN = 'minirefresh-hidden';
     bindEvent('.nav-control p', function(e) {
                var type = this.getAttribute('list-type');             
                type = +type;
                if(type!=3){
                    alert('此功能正在开发中...');
                    return;
                }
                if (type !== currIndex) {
                    navControl.querySelector('.active').classList.remove('active');
                    this.classList.add('active');                    
                    document.querySelector('#minirefresh' + currIndex).classList.add(CLASS_HIDDEN);
                    document.querySelector('#minirefresh' + type).classList.remove(CLASS_HIDDEN);                    
                    currIndex = type;                    
                    if (!miniRefreshArr[currIndex]) {
                        initMiniRefreshs(currIndex);
                    }
                }
            }, 'click');
            
            // 初始化
    initMiniRefreshs(3); 

    //图表创建  
        function drawCharts(x_data,y_data,info){
            var id=info.cahrtId,title=info.chartTitle,plot=info.chartPlot,index=info.index;
            var timesArr=new Array();
            var salesArr= new Array();
            for(var i=0;i<x_data.length;i++){
                timesArr.push(x_data[i]);
                salesArr.push(parseFloat(y_data[i]));
            }
            var option={
                title:{text:title},
                tooltip:{},
                legend:{data:['销售额']},
                xAxis:{data:timesArr},
                yAxis:{},
                grid:{x:45,y:50,x2:25,y2:25},
                series:[{
                    name:'销售额',
                    type:plot,
                    data:salesArr
                }]
            };
            
            var resizeOpt={
                width:windowWidth
            }
            if(index==0){
                chartview0.setOption(option);
                chartview0.resize(resizeOpt);
            }else if(index==1){
                chartview1.setOption(option);
                chartview1.resize(resizeOpt);
            }else if(index==2){
                var dataArr=new Array();
                //取前十位
                if(timesArr.length<10){
                    for(var i=0;i<timesArr.length;i++){
                    var dobj={value:salesArr[i],name:timesArr[i]};
                    dataArr.push(dobj);
                    }
                }else{
                     for(var i=0;i<10;i++){
                    var dobj={value:salesArr[i],name:timesArr[i]};
                    dataArr.push(dobj);
                    }
                }
                
                option={
                title:{
                    text:title,
                    x:'center'
                },
                tooltip:{
                    trigger:'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend:{
                   data: ['国家']
                },
                 series : [
                    {
                        name: '流量分布',
                        type: 'pie',
                        radius : '55%',
                        center: ['50%', '60%'],
                        data:dataArr,
                        itemStyle: {
                            emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                      }
                                    }
                     }
                  ]
             }
                chartview2.setOption(option);
                chartview2.resize(resizeOpt);
            }else{
                chartview3.setOption(option);
                chartview3.resize(resizeOpt);
            }
            
             
        }           
    });
      